package com.borya.filter;

import com.borya.dao.ServerConfDAO;
import com.borya.framework.annotation.Autowired;
import com.borya.framework.util.ObjectUtils;
import io.netty.util.CharsetUtil;

import java.util.HashSet;
import java.util.List;
import java.util.function.Predicate;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import com.alibaba.fastjson.JSONObject;
import com.borya.framework.annotation.Filter;
import com.borya.framework.core.ServerFilter;
import com.borya.framework.core.ServerRequest;
import com.borya.framework.core.ServerResponse;
import com.borya.statuscode.StatusCode;


@Filter
public class S2SFilter implements ServerFilter {


    private Logger log = Logger.getLogger(getClass());
    private HashSet<String> URL_NEED;
    @Autowired("serverConfDAOImpl")
    private ServerConfDAO serverConfDAO;

    public S2SFilter() {
        this.URL_NEED = new HashSet<String>();
        URL_NEED.add("/s/user/getSmsCode");
        URL_NEED.add("/s/user/shqpInfo");
    }

    @Override
    public boolean doFilter(ServerRequest request, ServerResponse response) {
        final String url = request.uri();

        Predicate<String> pre = str -> !str.contains("/s/");
        boolean test = pre.test(url);
        if (test) {
            return false;
        }
        String ip = request.headers().get("http_x_forwarded_for");
        final String host = ObjectUtils.isNullOrEmpty(ip) ? request.ip() : ip;
        final String text = request.text();
        if (url.contains("/s/ping/get")) {
            response.content().writeBytes(StatusCode.SUCCESS.toJSON().getBytes(CharsetUtil.UTF_8));
            return true;
        }
        if (url.contains("/s/autoResource/ready")) {
            log.info("自动入库启动");
            return false;
        }

        /** 秦波新加，更改门店使用地区、用户使用人信息专用限制**/
        if (url.endsWith("/s/user/userClientAndRegion")) {
            log.info("更改门店使用地区host:" + host);
            if (host.equals("127.0.0.1") || host.equals("172.16.95.255")
                    || host.equals("172.16.84.54") || host.equals("192.168.10.60")) {
                return false;
            }
        }

        if (URL_NEED.contains(url)) {
            List<String> allowIps = serverConfDAO.allowIps();

            if (!allowIps.contains(host)) {
                log.warn(String.format("ip limit,get:%s,url:%s,text:%s", host, url, test));
                response.content().writeBytes(StatusCode.FORBID.toJSON().getBytes(CharsetUtil.UTF_8));
                return true;
            }
        }

        pre = str -> StringUtils.isBlank(str);
        if (pre.test(text)) {
            log.warn("[" + host + "] Server recv is empty,url=" + url);
            response.content().writeBytes(StatusCode.FORBID.toJSON("数据为空").getBytes(CharsetUtil.UTF_8));
            return true;
        }
        if (log.isTraceEnabled())
            log.trace(url + "拦截器 RECV:" + text);
        try {
            JSONObject json = JSONObject.parseObject(text);
            if (json == null) {
                log.warn("[" + host + "] Parse json error,url=" + url);
                response.content().writeBytes(StatusCode.PARAM_ERROR.toJSON("数据格式错误").getBytes(CharsetUtil.UTF_8));
                return true;
            }

            request.setAttribute("json", json);
            return false;
        } catch (Exception e) {
            log.error(e.getMessage() + " url=" + url, e);
            response.content().writeBytes(StatusCode.FORBID.toJSON("数据格式错误").getBytes(CharsetUtil.UTF_8));
            return true;
        }
    }

}